<template>
  <el-form ref="applyDataField" size="small" :rules="ruleValidate" :model="applyData" label-width="140px" @submit.native.prevent>
    <el-row :gutter="24" class="mt20">
      <el-col :span="12">
        <el-form-item label="活动名称：" prop="activity_name">
          <el-input v-model="applyData.activity_name" maxlength="50" placeholder="请输入活动名称" show-word-limit />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="活动分类：" prop="cate_id">
          <el-select v-model="applyData.cate_id" placeholder="请选择" class="selWidth">
            <el-option v-for="item in categoryList" :key="item.category_id" :label="item.cate_name" :value="item.category_id"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="起止时间：" required>
          <el-date-picker v-model="timeVal" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" type="datetimerange" placement="bottom-end" placeholder="请选择活动时间" @change="onchangeTime"/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="活动简介：">
          <el-input type="textarea" maxlength="500" v-model="applyData.info" :autosize="{ minRows: 4, maxRows: 8}" show-word-limit placeholder="请输入活动简介" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="背景色：">
          <el-color-picker v-model="applyData.color"></el-color-picker>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-form-item label="封面图：" prop="pic">
        <div class="upLoadPicBox" title="710*340px" @click="modalPicTap('1')">
        <div v-if="applyData.pic" class="pictrue">
          <img :src="applyData.pic">
        </div>
        <div v-else class="upLoad">
          <i class="el-icon-camera" />
        </div>
      </div>
      <div style="color: #ccc;font-size: 12px;">建议尺寸750*350px</div>
      </el-form-item>
    </el-row>
    <el-row>
      <el-form-item label="分享海报：" prop="images">
        <div class="acea-row">
          <div v-for="(item,index) in applyData.images" :key="index" class="pictrue">
            <img :src="item" @click="lookImg(item)">
          <i class="el-icon-error btndel" @click="handleRemove(index)" />
          </div>
          <div v-if="applyData.images.length < 5" class="upLoadPicBox" @click="modalPicTap('2')">
            <div class="upLoad">
              <i class="el-icon-camera" />
            </div>
          </div>
        </div>
        <div style="color: #ccc;font-size: 12px;">
        建议尺寸750*1250px
      </div>
      </el-form-item>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="排序：">
          <el-input-number v-model="applyData.sort" controls-position="right" placeholder="请输入排序"/>
        </el-form-item>
      </el-col>
      <el-col :span="12">
       <el-form-item label="活动人数：">
          <el-input-number v-model="applyData.count" controls-position="right" placeholder="请输入本次活动总人数"/>
          <span>0为不限制人数</span>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
        <el-form-item label="价格：">
            <el-input-number v-model="applyData.price" controls-position="right" placeholder="请输入本次活动价格"/>
        </el-form-item>
    </el-row>
    <el-row>
      <el-form-item label="是否核销：">
        <el-switch v-model="applyData.is_hexiao" :active-value="1" :inactive-value="0" :width="55" active-text="开启" inactive-text="关闭"/>
      </el-form-item>
    </el-row>
    
    <!-- 悬赏活动专属字段 -->
    <el-row v-if="applyData.type == 1">
      <el-form-item label="活动类型：">
        <el-select v-model="applyData.type" disabled>
          <el-option label="悬赏活动" :value="1"/>
        </el-select>
        <span style="color: #999; margin-left: 10px;">该页面仅用于悬赏活动</span>
      </el-form-item>
    </el-row>
    <el-row v-if="applyData.type == 1">
      <el-form-item label="年龄段：">
        <div class="acea-row">
          <el-input-number v-model="minAge" placeholder="最小年龄" controls-position="right" style="width: 100px;" :min="18" :max="75" />
          <span style="margin: 0 10px;">-</span>
          <el-input-number v-model="maxAge" placeholder="最大年龄" controls-position="right" style="width: 100px;" :min="18" :max="75" />
        </div>
      </el-form-item>
    </el-row>
    <el-row v-if="applyData.type == 1">
      <el-form-item label="性别：">
        <el-select v-model="applyData.sex" placeholder="请选择性别限制">
          <el-option label="不限" :value="-1" />
          <el-option label="男" :value="0" />
          <el-option label="女" :value="1" />
        </el-select>
      </el-form-item>
    </el-row>
    <el-row v-if="applyData.type == 1">
      <el-form-item label="健康情况：">
        <el-select v-model="applyData.health" placeholder="请选择健康情况">
          <el-option label="不限" :value="'不限'" />
          <el-option label="正常" :value="'正常'" />
          <el-option label="传染病" :value="'传染病'" />
          <el-option label="重大疾病" :value="'重大疾病'" />
          <el-option label="其他" :value="'其他'" />
        </el-select>
      </el-form-item>
    </el-row>
    <el-row v-if="applyData.type == 1">
      <el-form-item label="参与过是否可报名：">
        <el-switch :width="80" v-model="applyData.is_repeat" :active-value="1" :inactive-value="0" active-text="允许" inactive-text="不允许"/>
      </el-form-item>
    </el-row>
    <el-row v-if="applyData.type == 1">
      <el-form-item label="是否上传报名凭证：">
        <el-switch :width="80" v-model="applyData.is_proof" :active-value="1" :inactive-value="0" active-text="需要" inactive-text="不需要"/>
      </el-form-item>
    </el-row>
    <el-row>
      <el-form-item label="是否显示：">
        <el-switch v-model="applyData.is_show" :active-value="1" :inactive-value="0" :width="55" active-text="开启" inactive-text="关闭"/>
      </el-form-item>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="关联表单：" prop="link_id">
          <div class="acea-row">
            <el-select v-model="applyData.link_id" @change="getFormInfo" placeholder="请选择" clearable>
              <el-option v-for="item in formList" :key="item.form_id" :label="item.name" :value="item.form_id"/>
            </el-select>
            <div style="margin-left: 20px">
              <router-link target="_blank" :to="{ path: `${roterPre}` + '/systemForm/form_create', query: { id: applyData.link_id } }">
                <el-button type="text">编辑表单</el-button>
              </router-link>
            </div>
          </div>
        </el-form-item>
        <el-form-item v-if="applyData.link_id">
          <div style="width: 350px;">
            <iframe id="iframe" class="iframe-box" :src="formUrl" frameborder="0" ref="iframe" style="min-height: 300px;"></iframe>
          </div>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="活动详情：">
          <ueditorFrom v-model="applyData.content" :content="applyData.content" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="更新时间：">
          {{applyData.update_time}}
        </el-form-item>
      </el-col>
    </el-row>
    <div class="images" v-show="false" v-viewer="{ movable: false }">
      <img v-for="(src,index) in applyData.images" :src="src" :key="index" />
    </div>
</el-form>
</template>
<script>
import SettingMer from '@/libs/settingMer'
import { associatedFormList } from '@/api/product'
import { activityCateSelect, activityUpdateApi } from '@/api/activity'
import {getToken} from "@/utils/auth";
import ueditorFrom from '@/components/ueditorFrom'
import {roterPre} from "@/settings";

export default {
  components: {
    ueditorFrom
  },
  props: {
    applyData: {
      type: Object,
      default: {},
    },
    isAdd: {
      type: Boolean,
      default: false,
    },

  },
  data() {
    // 初始化年龄段默认值
    let minAge = 18;
    let maxAge = 75;
    if(this.applyData.type == 1 && this.applyData.ages){
      const ageParts = this.applyData.ages.split(',');
      if(ageParts.length === 2){
        minAge = parseInt(ageParts[0]) || 18;
        maxAge = parseInt(ageParts[1]) || 75;
      }
    }
    
    return {
      roterPre: roterPre,
      loading: false,
      listLoading: false,
      applyId: "",
      direction: 'rtl',
      activeName: 'detail',
      formUrl: "",
      // BaseURL: 'http://localhost:8080',
      BaseURL: SettingMer.httpUrl || 'http://localhost:8080',
      timeVal: [this.applyData.start_time,this.applyData.end_time],
      ruleValidate: {
        activity_name: [{ required: true,message: "请输入活动名称", trigger: "blur"}],
        // link_id: [{ required: true, message: '请选择关联表单', trigger: 'change' }],
        pic: [{ required: true, message: '请上传封面图', trigger: 'change' }],
        images: [{ required: true, message: '请上传海报图', trigger: 'change' }],

      },
      formList: [],
      formData: [],
      categoryList: [], // 分类筛选
      
      // 设置默认值，避免初次渲染时出现undefined
      minAge: minAge,
      maxAge: maxAge,
    };
  },
  watch: {
    applyData: function(n) {
      this.timeVal = [n.start_time,n.end_time];
      
      // 处理年龄段数据，将"min,max"格式拆分为minAge和maxAge
      if(n.type == 1 && n.ages){
        const ageParts = n.ages.split(',');
        if(ageParts.length === 2){
          this.applyData.minAge = parseInt(ageParts[0]) || 18;
          this.applyData.maxAge = parseInt(ageParts[1]) || 75;
        }
      }
    },
  },
  filters: {
  },
  mounted() {
    let time = new Date().getTime() * 1000
    let formUrl = `${this.BaseURL}/pages/admin/system_form/index?inner_frame=1&time=${time}&form_id=${this.applyData.link_id}`;
    this.formUrl = formUrl;
  },
  methods: {
    addCustomDialog(editorId) {
      window.UE.registerUI(
        "test-dialog",
        function(editor, uiName) {
          // 创建 dialog
          let dialog = new window.UE.ui.Dialog({
            iframeUrl: roterPre + "/admin/widget/image?field=dialog",
            editor: editor,
            name: uiName,
            title: "上传图片",
            cssRules: "width:1200px;height:500px;padding:20px;"
          });
          this.dialog = dialog;
          let btn = new window.UE.ui.Button({
            name: "dialog-button",
            title: "上传图片",
            cssRules: `background-image: url(../../../assets/images/icons.png);background-position: -726px -77px;`,
            onclick: function() {
              // 渲染dialog
              dialog.render();
              dialog.open();
            }
          });
          return btn;
        },
        37
      );
      window.UE.registerUI(
        "video-dialog",
        function(editor, uiName) {
          let dialog = new window.UE.ui.Dialog({
            iframeUrl: roterPre + "/admin/widget/video?fodder=video",
            editor: editor,
            name: uiName,
            title: "上传视频",
            cssRules: "width:600px;height:420px;padding:10px 20px 20px;"
          });
          this.dialog = dialog;
          let btn = new window.UE.ui.Button({
            name: "video-button",
            title: "上传视频",
            cssRules: `background-image: url(../../../assets/images/icons.png);background-position: -320px -20px;`,
            onclick: function() {
              // 渲染dialog
              dialog.render();
              dialog.open();
            }
          });
          return btn;
        },
        38
      );
    },
    // 活动起止日期
    onchangeTime(e) {
      this.timeVal = e
      this.applyData.start_time = e ? e[0] : ''
      this.applyData.end_time = e ? e[1] : ''
    },
     // 点击商品图
    modalPicTap(tit, num, i) {
      const _this = this;
      this.$modalUpload(function(img) {
        if (tit === "1") {
          _this.applyData.pic = img[0];
        }
        if (tit === '2') {
          img.map((item) => {
            _this.applyData.images.push(item)
            if (_this.applyData.images.length > 5) {
              _this.applyData.images.length = 5
            }
          })
        }
      }, tit);
    },
    handleRemove(i) {
      this.applyData.images.splice(i, 1)
    },
    lookImg(src) {
      const viewer = this.$el.querySelector('.images').$viewer;
      viewer.show();
      this.$nextTick(() => {
        let i = this.applyData.images.findIndex((e) => e === src);
        viewer.update().view(i);
      });
    },
    /**重置表单数据 */
    resetData(){
      this.$refs.applyDataField.resetFields();
    },
     // 获取系统表单下拉数据
    getFormSelect(){
        associatedFormList().then((res) => {
        this.formList = res.data
      })
      .catch((res) => {
        this.$message.error(res.message)
      })
    },
    getCategoryList() {
      activityCateSelect()
        .then(res => {
          this.categoryList = res.data
        })
        .catch(res => {
          this.$message.error(res.message)
        })
    },
    // 关联的表单信息
    getFormInfo(){
      if(this.applyData.link_id){
        let time = new Date().getTime() * 1000
        let formUrl = `${this.BaseURL}/pages/admin/system_form/index?inner_frame=1&form_id=${this.applyData.link_id}&time=${time}`;
        this.formUrl = formUrl;
      }
    },
    /*提交信息*/
    onSubmit(id){
      if(!this.timeVal){
        this.$message.warning('请选择活动时间！');
      }else{
        this.$refs['applyDataField'].validate(valid => {
          if (valid) {
            this.loading = true;
            this.applyData.form_id = this.applyData.link_id;
            
            // 处理年龄段数据
            if(this.applyData.type == 1){
              this.applyData.ages = `${this.minAge},${this.maxAge}`;
            }
            
            activityUpdateApi(id,this.applyData)
            .then(async res => {
              this.$message.success(res.message);
              this.loading = false;
              this.$emit('success');
            })
            .catch(res => {
              this.loading = false;
              this.$message.error(res.message);
            });
          }
       });
      }
    },
    /**创建商户 */
    handleCreate(){
      this.$refs['applyDataField'].validate((valid) => {
        if (valid) {
          merchantCreate(this.applyData)
            .then(async (res) => {
              this.$message.success(res.message);
              this.$emit('success');
            })
            .catch((res) => {
              this.$message.error(res.message);
            });
        } else {
          if(!this.applyData.mer_name)return this.$message.error('请填写基本信息-商户名称');

        }
      });
    }
  },
};
</script>
<style lang="scss" scoped>
.el-tabs--border-card {
  box-shadow: none;
  border-bottom: none;
}
.section {
  padding: 20px 0 8px;
  border-bottom: 1px dashed #eeeeee;
  .title {
    padding-left: 10px;
    border-left: 3px solid var(--prev-color-primary);
    font-size: 15px;
    line-height: 15px;
    color: #303133;
  }
  .list {
    display: flex;
    flex-wrap: wrap;
    list-style: none;
    padding: 0;
  }
  .item {
    flex: 0 0 calc(100% / 2);
    display: flex;
    margin-top: 16px;
    font-size: 13px;
    color: #606266;

    &:nth-child(2n + 1) {
      padding-right: 20px;
      padding-left: 20px;
    }
    &:nth-child(2n) {
     padding-right: 20px;
    }
  }
  .value {
    flex: 1;
    image {
      display: inline-block;
      width: 40px;
      height: 40px;
      margin: 0 12px 12px 0;
      vertical-align: middle;
    }
  }
}
.info-red{
  color: red;
  font-size: 12px;
}
::v-deep .el-input-number.is-controls-right .el-input__inner{
 padding: 0 40px 0 10px;
}
::v-deep .el-form-item__label{
  font-weight: normal;
  color: #282828;
}
::v-deep .specsList th {
  line-height: 20px!important;
}
.tab {
  display: flex;
  align-items: center;
  .el-image {
    width: 36px;
    height: 36px;
    margin-right: 10px;
  }
}
::v-deep .el-drawer__body {
  overflow: auto;
}
.gary {
  color: #aaa;
}
.pictrue{
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0,0,0,0.1);
  margin-right: 10px;
  position: relative;
  cursor: pointer;
  img{
    width: 100%;
    height: 100%;
  }
  .btndel {
    position: absolute;
    z-index: 1;
    width: 20px !important;
    height: 20px !important;
    left: 46px;
    top: -4px;
  }
}
::v-deep .el-input .el-input__count .el-input__count-inner{
  background: #ffffff;
}
</style>
